<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <base href="<%=basePath%>">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <%@ include file="top.jsp" %>

    <title>房间管理</title>
    <script type="text/javascript">
        jQuery(function () {
            $.extend($.fn.validatebox.defaults.rules, {
                //新增房间重复验证
                roomAreaNameRepetition: {
                    validator: function (value) {
                        var b = false;
                        $.ajax({
                            type: "post", dataType: "text", async: false,
                            data: {
                                areaName: value
                            },
                            url: "roomAction!isExistRoom",
                            success: function (data) {
                                if (data == 'true') {
                                    b = true;
                                }
                            }
                        });
                        return b ? true : false;
                    },
                    message: '该房间已存在'
                }
            });

            $('form[name="edit1"] input[name="roomName"]').validatebox({
                required: true,
                validType: 'length[2,30]',
                missingMessage: '请输入名',
                invalidMessage : '名长度为2-30 位'
            });
            //搜索框初始化
            $('form[name="search"] #param_hotelId').combobox({
                editable :       false,
                panelHeight: 'auto',
                url: 'hotelAction!getHotelName',
                method: 'post',
                valueField: 'hotelId',
                textField: 'hotelName'
            });

            $('form[name="search"] #param_roomType').combobox({
                editable :       false,
                invalidMessage: '请选择房间类型',
                panelHeight: 'auto',
                url: 'roomAction!getRoomType',
                method: 'post',
                valueField: 'roomType',
                textField: 'roomType'
            });

            //新增房间
            jQuery("#add_div").dialog({
                width: 600,
                height: 350,
                algin: 'center',
                title: '新增房间',
                modal: true,
                closed: true,
                href: 'roomAction!addPage',
                iconCls: 'icon-user_add',
                buttons: [
                    {
                        id: 'button_1',text: '提交', iconCls: 'icon-add-new', handler: function () {
                        jQuery('#button_1').linkbutton('disable');

                        if ($('#add').form('validate')) {
                            var formData  = new FormData($( "#add" )[0]);
                            $.ajax({
                                url: 'roomAction!addRoom',
                                type: 'post',
                                dataType: 'json',
                                data: formData ,
                                cache: false,
                                contentType: false,
                                processData: false,
                                beforeSend: function () {
                                    $.messager.progress({text: '正在新增中...'});
                                },
                                success: function (jsonData, response, status) {
                                    jQuery('#button_1').linkbutton('enable');
                                    $.messager.progress('close');
                                    $('#add_div').dialog('close');
                                    var flag = jsonData.flag;
                                    var errorMsg = jsonData.msg;
                                    if (flag == true) {
                                        jQuery("#grid_div").datagrid("reload");
                                        $('#add').form('reset');
                                        $('#add_div').dialog('close');
                                        jQuery.messager.confirm("继续添加", errorMsg, function (r) {
                                            if (r) {
                                                $('#add_div').dialog('open');
                                            } else {
                                                jQuery("#grid_div").datagrid("reload");
                                            }
                                        });
                                    } else {
                                        $.messager.alert("操作提示", "操作失败，原因 = " + errorMsg, "warning");
                                        jQuery("#grid_div").datagrid("reload");
                                    }
                                }
                            });
                        }else{
                            jQuery('#button_1').linkbutton('enable');
                        }
                    }
                    }, {
                        text: '取消', iconCls: 'icon-redo', handler: function () {
                            $('#add').form('reset');
                            $('#add_div').dialog('close');
                        }
                    }]
            });

            //修改房间
            jQuery("#edit").dialog({
                width: 600,
                height: 350,
                algin: 'center',
                title: '修改房间',
                modal: true,
                closed: true,
                iconCls: 'icon-edit',
                buttons: [
                    {
                        id: 'button_1', text: '提交', iconCls: 'icon-edit-new', handler: function () {
                        jQuery('#button_1').linkbutton('disable');
                        if ($('#edit').form('validate')) {
                            var formData  = new FormData($( "#edit1" )[0]);
                            $.ajax({
                                url: 'roomAction!editRoom',
                                type: 'post',
                                dataType: 'json',
                                data: formData ,
                                cache: false,
                                contentType: false,
                                processData: false,
                                beforeSend: function () {
                                    $.messager.progress({text: '正在修改中...'});
                                },
                                success: function (jsonData, response, status) {
                                    $.messager.progress('close');
                                    $('#edit').dialog('close');
                                    var flag = jsonData.flag;
                                    var errorMsg = jsonData.msg;
                                    jQuery('#button_1').linkbutton('enable');
                                    if (flag == true) {
                                        jQuery("#grid_div").datagrid("reload");
                                        $('#edit').dialog('close');
                                        jQuery.messager.confirm("确认修改", errorMsg, function (r) {
                                            if (!r) {
                                                $('#edit').dialog('open');
                                            } else {
                                                jQuery("#grid_div").datagrid("reload");
                                            }
                                        });
                                    } else {
                                        $.messager.alert("操作提示", "操作失败，原因 = " + errorMsg, "warning");
                                        jQuery("#grid_div").datagrid("reload");
                                    }
                                }
                            });
                        } else{
                            jQuery('#button_1').linkbutton('enable');
                        }
                    }
                    }, {
                        text: '取消', iconCls: 'icon-redo', handler: function () {
                            $('#edit').dialog('close')
                            $("#edit1").form('reset');
                        }
                    }]
            });


            //数据显示
            jQuery('#grid_div').datagrid({
                url: 'roomAction!listGrid',
                fit: true,
                fitColumns: true,
                striped: true,
                loadMsg: "加载数据",
                rownumbers: true,
                border: false,
                pagination: true,
                pageSize: 10,
                pageList: [5, 10, 15, 20, 25],
                pageNumber: 1,
                sortName: 'roomId',
                sortOrder: 'asc',
                toolbar: '#grid_tool',
                remoteSort: true,
                frozenColumns: [[                                //锁列
                    {field: "ck", checkbox: true, width: 30},
                    {field: "roomId", title: "房间ID", width: 50}
                ]],
                columns: [[
                    {field: "roomName", title: "房间名称", width: 150, align: "left", halign: "center", sortable: true},
                    {field: "roomType", title: "房间类型", width: 150, align: "left", halign: "center", sortable: true},
                    {field: "roomPay", title: "房间价格", width: 150, align: "left", halign: "center", sortable: true},
                    {field: "hotel", title: "所属酒店", width: 150, align: "left", halign: "center", sortable: true,
                        formatter: function(value, row, index){
                            if(value != null){
                                return value.hotelName;
                            }
                        }
                    },
                    {field: "roomDesc", title: "房间描述", width: 150, align: "left", halign: "center"},

                ]],
                //操作事件
                onRowContextMenu: function (e, rowIndex, rowData) {
                    e.preventDefault();
                    $('#right_click').menu('show', {
                        left: e.pageX,
                        top: e.pageY
                    });
                }
            });

            //按钮事件
            grid_tool = {
                //刷新
                reload: function () {
                    jQuery('#grid_div').datagrid('reload');
                },
                //撤销
                redo: function () {
                    $('#grid_div').datagrid('unselectAll');
                    $('#search').form('clear');

                },
                //添加
                add: function () {
                    $('#add_div').dialog('open');
                    $('input[name="roomName"]').focus();
                },
                //搜索
                search: function () {
                    var param_roomName = jQuery("#param_roomName").val();
                    var param_roomType = jQuery("#param_roomType").combobox('getValue');
                    var param_hotelId = jQuery("#param_hotelId").combobox('getValue');
                    var param_roomPayMin = jQuery("#param_roomPayMin").val();
                    var param_roomPayMax = jQuery("#param_roomPayMax").val();
                    var param_roomDesc = jQuery("#param_roomDesc").val();
					var param_roomStatus = jQuery("#param_roomStatus").val();
                    var paramObj = {
                        "param_roomName": param_roomName,
                        "param_roomType": param_roomType,
                        "param_hotelId":param_hotelId,
                        "param_roomPayMin":param_roomPayMin,
                        "param_roomPayMax":param_roomPayMax,
                        "param_roomDesc":param_roomDesc,
                        "param_roomStatus":param_roomStatus
                    };
                    jQuery("#grid_div").datagrid({
                        queryParams: paramObj
                    });
                },
                //删除
                remove: function () {
                    var selectArray = $('#grid_div').datagrid('getSelections');
                    if (selectArray == null || selectArray.length == 0) {
                        $.messager.alert("操作提示", "你还还未选中记录，不能执行删除操作", "warning");
                    } else {
                        $.messager.confirm('确定操作', '您正在要删除所选的记录吗？', function (flag) {
                            if (flag) {
                                var ids = [];
                                for (var i = 0; i < selectArray.length; i++) {
                                    ids.push(selectArray[i].roomId);
                                }
                                jQuery.ajax({
                                    type: 'POST',
                                    url: 'roomAction!deleteRoomById',
                                    data: {
                                        ids: ids.join(',')
                                    },
                                    dataType: 'json',
                                    success: function (jsonData) {
                                        var flag = jsonData.flag;
                                        var errorMsg = jsonData.msg;
                                        if (flag == true) {
                                            jQuery("#grid_div").datagrid("reload");
                                            $.messager.show({title: '提示', msg: errorMsg, timeout: 2000});
                                        } else {
                                            $('#grid_div').datagrid('unselectAll');
                                            $.messager.alert("操作提示", "操作失败，原因 = " + errorMsg, "warning");
                                            jQuery("#grid_div").datagrid("reload");
                                        }
                                    }
                                });
                            }
                        });
                    }
                },
                //编辑
                edit: function () {
                    var selectArray = $('#grid_div').datagrid('getSelections');
                    if (selectArray.length > 1) {
                        $.messager.alert('警告操作！', '编辑记录只能选定一条数据！', 'warning');
                    } else if (selectArray.length == 1) {

                        $.ajax({
                            url: 'roomAction!getRoomById',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                roomId: selectArray[0].roomId
                            },
                            beforeSend: function () {
                                $.messager.progress({text: '正在获取中...'});
                            },
                            success: function (jsonData, response, status) {
                                $.messager.progress('close');
                                var flag = jsonData.flag;
                                var msg = jsonData.msg;

                                $('form[name="edit1"] #hotelId').combobox({
                                    mode: 'remote',
                                    required: true,
                                    //editable :       false,
                                    invalidMessage: '请选择酒店',
                                    panelHeight: 'auto',
                                    url: 'hotelAction!getHotelName',
                                    method: 'post',
                                    valueField: 'hotelId',
                                    textField: 'hotelName'
                                });
                                var hotelId= "";
                                if(msg.hotel != null){
                                    hotelId = msg.hotel.hotelId
                                }
                                if (flag) {
                                    $('#edit').form('load', {
                                        roomId: msg.roomId,
                                        roomName: msg.roomName,
                                        hotelId: hotelId,
                                        roomType: msg.roomType,
                                        roomPay: msg.roomPay,
                                        roomDesc: msg.roomDesc,
                                    }).dialog('open');

                                } else {
                                    $.messager.alert("操作提示", "操作失败，原因 = " + msg, "warning");
                                }
                            }
                        });
                    } else if (selectArray.length == 0) {
                        $.messager.alert('警告操作！', '编辑记录至少选定一条数据！', 'warning');
                    }
                }
            };

           // $(form).on("change","#roomPicture",change_photo);
        })


        function change_photo(){
            PreviewImage($("input[name='picture']")[0], 'Img', 'Imgdiv');
        }

        function PreviewImage(fileObj,imgPreviewId,divPreviewId){
            var allowExtention=".jpg,.bmp,.gif,.png";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
            var extention=fileObj.value.substring(fileObj.value.lastIndexOf(".")+1).toLowerCase();
            var browserVersion= window.navigator.userAgent.toUpperCase();
            if(allowExtention.indexOf(extention)>-1){
                if(fileObj.files){//HTML5实现预览，兼容chrome、火狐7+等
                    if(window.FileReader){
                        var reader = new FileReader();
                        reader.onload = function(e){
                            document.getElementById(imgPreviewId).setAttribute("src",e.target.result);
                        }
                        reader.readAsDataURL(fileObj.files[0]);
                    }else if(browserVersion.indexOf("SAFARI")>-1){
                        alert("不支持Safari6.0以下浏览器的图片预览!");
                    }
                }else if (browserVersion.indexOf("MSIE")>-1){
                    if(browserVersion.indexOf("MSIE 6")>-1){//ie6
                        document.getElementById(imgPreviewId).setAttribute("src",fileObj.value);
                    }else{//ie[7-9]
                        fileObj.select();
                        if(browserVersion.indexOf("MSIE 9")>-1)
                            fileObj.blur();//不加上document.selection.createRange().text在ie9会拒绝访问
                        var newPreview =document.getElementById(divPreviewId+"New");
                        if(newPreview==null){
                            newPreview =document.createElement("div");
                            newPreview.setAttribute("id",divPreviewId+"New");
                            newPreview.style.width = document.getElementById(imgPreviewId).width+"px";
                            newPreview.style.height = document.getElementById(imgPreviewId).height+"px";
                            newPreview.style.border="solid 1px #d2e2e2";
                        }
                        newPreview.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
                        var tempDivPreview=document.getElementById(divPreviewId);
                        tempDivPreview.parentNode.insertBefore(newPreview,tempDivPreview);
                        tempDivPreview.style.display="none";
                    }
                }else if(browserVersion.indexOf("FIREFOX")>-1){//firefox
                    var firefoxVersion= parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
                    if(firefoxVersion<7){//firefox7以下版本
                        document.getElementById(imgPreviewId).setAttribute("src",fileObj.files[0].getAsDataURL());
                    }else{//firefox7.0+
                        document.getElementById(imgPreviewId).setAttribute("src",window.URL.createObjectURL(fileObj.files[0]));
                    }
                }else{
                    document.getElementById(imgPreviewId).setAttribute("src",fileObj.value);
                }
            }else{
                alert("仅支持"+allowExtention+"为后缀名的文件!");
                fileObj.value="";//清空选中文件
                if(browserVersion.indexOf("MSIE")>-1){
                    fileObj.select();
                    document.selection.clear();
                }
                fileObj.outerHTML=fileObj.outerHTML;
            }
        }
    </script>
</head>
<body>
<div id="right_click" class="easyui-menu" style="width:120px;display:none;">
    <div iconCls="icon-add-new" onclick="grid_tool.add();">添加</div>
    <div iconCls="icon-edit-new" onclick="grid_tool.edit();">修改</div>
    <div iconCls="icon-delete-new" onclick="grid_tool.remove();">删除</div>
    <div iconCls="icon-reload" onclick="grid_tool.reload();">刷新</div>
    <div iconCls="icon-cancel" onclick="grid_tool.redo();">取消选择</div>
</div>
<div id="grid_tool" style="padding:5px;">
    <div style="margin-bottom:5px;">
        <a class="easyui-linkbutton" iconCls="icon-add-new" plain="true" onclick="grid_tool.add();">添加</a>
        <a class="easyui-linkbutton" iconCls="icon-edit-new" plain="true" onclick="grid_tool.edit();">修改</a>
        <a class="easyui-linkbutton" iconCls="icon-delete-new" plain="true" onclick="grid_tool.remove();">删除</a>
        <a class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="grid_tool.reload();">刷新</a>
        <a class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="grid_tool.redo();">取消选择</a>
    </div>
    <div style="padding:0 0 0 7px;color:#333;">
        <form id="search" name="search">
            <p>
                房间名称：<input type="text" class="textbox" name="param_roomName" id="param_roomName" style="width:110px">
                房间价格：<input type="text" class="textbox" name="param_roomPayMin" id="param_roomPayMin" style="width:110px">
                ——<input type="text" class="textbox" name="param_roomPayMax" id="param_roomPayMax" style="width:110px">
                房间描述: <input type="text" class="textbox" name="param_roomDesc" id="param_roomDesc" value=""/>
           	是否空房：
				<select id="param_roomStatus" style="width:205px">
					<option/>
					<option value="1">否</option>
					<option value="0">是</option>
				</select>
            </p>
            <p>
                所在酒店: <input type="text" class="easyui-combobox" name="param_hotelId" id="param_hotelId" value=""/>
                房间类型: <input type="text" class="easyui-combobox" name="param_roomType" id="param_roomType" value=""/>
                <a class="easyui-linkbutton" iconCls="icon-search" onclick="grid_tool.search();">查询</a>
            </p>
        </form>
    </div>
</div>
<div id="grid_div"></div>
<div id="add_div"></div>
<div id="edit">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'west',split:true" style="width:280px;">
    <form id="edit1" name="edit1" enctype="multipart/form-data" style="margin:0;padding:5px 0 0 20px;color:#333;">
        <table border="0">
            <input type="hidden" class="textbox" name="roomId" id="roomId" value=""/>
            <tr>
                <td>房间名称</td>
                <td><input type="text" class="textbox" name="roomName" id="roomName" value=""/></td>
            </tr>
            <tr>
                <td>房间价格</td>
                <td><input type="text" name="roomPay" id="roomPay"class="easyui-numberbox" precision="0"
                           max="99999" size="8" maxlength="8"  style="text-align:right; width: 160px"/></td>
            </tr>
            <tr>
                <td>房间类型</td>
                <td><input type="text" class="easyui-combobox" name="roomType" id="roomType" value=""/></td>
            </tr>
            <tr>
                <td>所属酒店</td>
                <td><input type="text" class="easyui-combobox" name="hotelId" id="hotelId" value=""/></td>
            </tr>
            <tr>
                <td>房间图片</td>
                <td></td>
            </tr>
            <tr>
                <td colspan="2"><input  type="file" onchange="change_photo()" name="picture" id="picture"/></td>
            </tr>
            <tr>
                <td>房间描述</td>
                <td><textarea cols="20" rows="3" name="roomDesc" id="roomDesc" style="	border-radius: 5px;-moz-border-radius: 5px;
			-webkit-border-radius: 5px;"></textarea>
            </tr>
        </table>
    </form>
        </div>
        <div data-options="region:'center'" style="padding:10px">
            <div id="Imgdiv">
                <img id="Img" width="100%" height="250px"/>
            </div>
        </div>
    </div>
</div>
<div id="dialog_div"></div>
</body>
</html>

